package de.tabreaderandroid.tabreader.model;

import java.util.LinkedList;
import java.util.List;

import de.tabreaderandroid.tabreader.utils.InvalidTabFormatException;

/**
 * @author André Stannek
 * 
 */
public class ChordedLine extends TabFileElement {

	private String chordLine;
	private String lyricsLine;

	/**
	 * Creates an new {@link ChordedLine} with an origin index.
	 * 
	 * @param originIndex
	 *            the index of the first line of this chorded line in the origin
	 *            document
	 * @see TabFileElement#TabFileElement(int)
	 */
	public ChordedLine(final int originIndex) {
		super(originIndex);
		chordLine = "";
		lyricsLine = "";
	}

	public String getChordLine() {
		return chordLine;
	}

	/**
	 * @param chordLine
	 *            the line with the cords
	 */
	public void setChordLine(final String chordLine) {
		this.chordLine = chordLine;
	}

	public String getLyricsLine() {
		return lyricsLine;
	}

	/**
	 * @param lyricsLine
	 *            the lyrics or the line below the chords
	 */
	public void setLyricsLine(final String lyricsLine) {
		if (lyricsLine == null) {
			this.lyricsLine = "";
		} else {
			this.lyricsLine = lyricsLine;
		}
	}

	@Override
	public String toString() {
		return chordLine + "\n" + lyricsLine + "\n";
	}

	@Override
	public List<String> getLines(int maxCharWidth)
			throws InvalidTabFormatException {
		List<String> result = new LinkedList<String>();
		String[] split = lyricsLine.split(" ");
		int i = 0;
		int offset = 0;
		while (i < split.length) {
			StringBuilder line = new StringBuilder();
			if (split[i].length() > maxCharWidth) {
				throw new InvalidTabFormatException(
						"A line in the tab was to long to display!");
			}
			while (i < split.length
					&& line.length() + split[i].length() + 1 < maxCharWidth) {
				line.append(split[i]).append(" ");
				i++;
			}
			result.add(chordLine.substring(
					Math.min(offset, chordLine.length()),
					Math.min(offset + line.length(), chordLine.length())));
			offset += line.length();
			result.add(line.toString());
		}
		return result;
	}
}
